import 'package:base_lib/common/base/base_bloc_page.dart';
import 'package:base_lib/index.dart';
import 'package:base_lib/router/parameters.dart';
import 'package:base_lib/theme/theme_global.dart';
import 'package:base_lib/utils/color_util.dart';
import 'package:doctor_examine_lib/common/widgets/input.dart';
import 'package:doctor_examine_lib/doctor_examine_componet.dart';
import 'package:doctor_examine_lib/examine_list/examine_list_entity.dart'
    as ExamineBean;
import 'package:doctor_examine_lib/offline_examine/offline_examine_bloc.dart';
import 'package:common_lib/patient_management/patient_list/patient_list_entity.dart'
    as PatientBean;
import 'package:doctor_examine_lib/hospital_list/hospital_list_entity.dart'
    as HospitalBean;
import 'package:flutter/material.dart';

class OffineExaminePage
    extends BaseBlocPage<OffineExamineBloc, _OffineExamineState> {
  OffineExaminePage(Parameters parameters) : super(parameters);

  @override
  _OffineExamineState generateThemeState() {
    return _OffineExamineState();
  }
}

class _OffineExamineState extends BaseBlocPageState<OffineExamineBloc> {
  void initState() {
    super.initState();
  }

  @override
  ignoreWindowWidget() => false;

  @override
  Widget buildChild(BuildContext context, MTheme theme) {
    return Scaffold(
      appBar: AppBar(
        title: Text("开具检查检验单"),
      ),
      backgroundColor: Colors.white,
      body: Container(
          color: Colors.white,
          child: SafeArea(
            child: Column(
              children: [
                Expanded(
                  child: SingleChildScrollView(
                    child: Column(
                      children: [
                        Divider(
                            height: 8.0,
                            thickness: 8.0,
                            color: theme.themeColor.themeBgColor),
                        StreamBuilder(
                          stream: bloc.patientInfoSubject,
                          builder: (context,
                              AsyncSnapshot<PatientBean.Datum> snapshot) {
                            return _addPatientBuilder(
                                context,
                                snapshot.hasData
                                    ? snapshot.data.patientName +
                                        "  " +
                                        Utils.returnGenderByInt(
                                            snapshot.data.sex) +
                                        "  " +
                                        DateUtil.returnAgeByBirthday(
                                            DateUtil.getDateTime(
                                                snapshot.data.birthDay))
                                    : "添加就诊人");
                          },
                        ),
                        Divider(height: 1),
                        _diagnoseInfoBuilder(),
                        StreamBuilder(
                          stream: bloc.hospitalInfoSubject,
                          builder: (context,
                              AsyncSnapshot<HospitalBean.Datum> snapshot) {
                            return _addHospitalBuilder(
                                context,
                                snapshot.hasData
                                    ? snapshot.data.orgName
                                    : "请选择检查医院");
                          },
                        ),
                        Divider(
                            height: 8.0,
                            thickness: 8.0,
                            color: theme.themeColor.themeBgColor),
                        _addExaminationItemBuilder(),
                        _addRemarkBuilder(),
                        _nextSpeBtnBuilder(context)
                      ],
                    ),
                  ),
                ),
              ],
            ),
          )),
    );
  }

  /// 添加患者
  Widget _addPatientBuilder(context, patientInfoStr) {
    return Container(
      margin: EdgeInsets.only(top: 10),
      padding: EdgeInsets.only(left: 16, right: 16),
      child: Column(
        children: [
          _cellHeaderWidget("就诊人信息", true),
          _cellWight(
            patientInfoStr,
            true,
            onTap: () {
              bloc.jumpToPatientListPage(context);
            },
          ),
        ],
      ),
    );
  }

  /// 初步诊断
  Widget _diagnoseInfoBuilder() {
    return Container(
      margin: EdgeInsets.only(top: 10),
      padding: EdgeInsets.only(left: 16, right: 16),
      child: Column(
        children: [
          _cellHeaderWidget("初步诊断", true),
          textareaWidget(
            placeholder: "请输入初步诊断信息",
            onChanged: (value) {
              bloc.editTentativeDiagnosis(value);
            },
          )
        ],
      ),
    );
  }

  /// 添加医院
  Widget _addHospitalBuilder(context, hospitalName) {
    return Container(
      margin: EdgeInsets.only(top: 10),
      padding: EdgeInsets.only(left: 16, right: 16),
      child: Column(
        children: [
          _cellHeaderWidget("检查医院", true),
          StreamBuilder(
            stream: bloc.hospitalInfoSubject,
            builder: (context, AsyncSnapshot<HospitalBean.Datum> snapshot) {
              return _cellWight(
                hospitalName,
                true,
                onTap: () {
                  bloc.selectExamineHospital(context);
                },
              );
            },
          ),
        ],
      ),
    );
  }

  /// 添加检查项目
  Widget _addExaminationItemBuilder() {
    return Container(
      margin: EdgeInsets.only(top: 10),
      padding: EdgeInsets.only(left: 16, right: 16),
      child: Column(
        children: [
          _cellHeaderWidget(
            "检查项目",
            true,
            rightIcon: Image.asset(
              "images/examine/examine_item_add.png",
              package: DoctorExamineComponent.assetsPackageName,
              width: 89.0,
              height: 15,
            ),
            onTap: () {
              bloc.addExamineItem(context);
            },
          ),
          _examineItemsListViewBuilder()
        ],
      ),
    );
  }

  Widget _examineItemsListViewBuilder() {
    return StreamBuilder<List<ExamineBean.SubDatum>>(
        stream: bloc.examineItemsSubject,
        builder: (context, snapshot) {
          return snapshot.hasData
              ? Column(
                  children: [
                    Column(
                      children: snapshot.data.map((e) {
                        return Container(
                          height: 40,
                          child: ListTile(
                            leading: GestureDetector(
                              onTap: () {
                                bloc.deleteExamineItem(e);
                              },
                              child: Icon(
                                Icons.delete,
                                color: Colors.red,
                              ),
                            ),
                            title: Text(e.examineClassName +
                                "-" +
                                e.attributeValue +
                                "-" +
                                e.examineItemName),
                            trailing: Text(
                              "¥ " + MoneyUtil.changeF2Y(e.personPay),
                              style: TextStyle(color: Colors.red),
                            ),
                          ),
                        );
                      }).toList(),
                    ),
                    Container(
                      alignment: Alignment.centerRight,
                      padding: EdgeInsets.only(right: 18, top: 18),
                      child: Text(
                        "合计：¥ " + MoneyUtil.changeF2Y(bloc.getSumPrice()),
                        style: TextStyle(color: Colors.red),
                      ),
                    )
                  ],
                )
              : Container();
        });
  }

  /// 添加备注
  Widget _addRemarkBuilder() {
    return Container(
      margin: EdgeInsets.only(top: 10),
      padding: EdgeInsets.only(left: 16, right: 16),
      child: Column(
        children: [
          _cellHeaderWidget("备注", false),
          textareaWidget(
            placeholder: "如果有补充内容，请在这里输入",
            onChanged: (value) {
              bloc.editNote(value);
            },
          )
        ],
      ),
    );
  }

  /// 下一步
  Widget _nextSpeBtnBuilder(context) {
    return Container(
      margin: EdgeInsets.only(top: 60),
      padding: EdgeInsets.only(left: 16, right: 16),
      width: double.infinity,
      height: 44,
      child: Container(
        decoration: BoxDecoration(
            gradient: LinearGradient(colors: [
              ColorUtil.color("#438BEF"),
              ColorUtil.color("#60B6FF")
            ]), // 渐变色
            borderRadius: BorderRadius.circular(2)),
        child: MaterialButton(
            textColor: Colors.white,
            child: new Text('下一步'),
            onPressed: () {
              bloc.nextHandler(context);
            }),
      ),
    );
  }

  Widget _cellHeaderWidget(String title, bool isMust,
      {Image rightIcon, VoidCallback onTap}) {
    return Container(
      height: 30,
      child: Row(
        children: [
          Offstage(
            offstage: !isMust,
            child: Text(
              "*",
              style: TextStyle(
                  color: Colors.red, fontWeight: FontWeight.w400, fontSize: 15),
            ),
          ),
          Text(
            title,
            style: TextStyle(
                color: ColorUtil.color("#787878"),
                fontWeight: FontWeight.w400,
                fontSize: 15),
          ),
          Spacer(),
          GestureDetector(
            onTap: onTap,
            child: Offstage(
              offstage: rightIcon == null,
              child: rightIcon,
            ),
          )
        ],
      ),
    );
  }

  Widget _cellWight(String content, bool isClick, {VoidCallback onTap}) {
    return GestureDetector(
        behavior: HitTestBehavior.opaque,
        onTap: onTap,
        child: Container(
          height: 50,
          child: Row(
            children: [
              Text(
                content,
                style: TextStyle(
                    color: ColorUtil.color("#999999"),
                    fontWeight: FontWeight.w400,
                    fontSize: 16),
              ),
              Spacer(),
              Offstage(
                offstage: !isClick,
                child: Icon(
                  Icons.arrow_forward_ios,
                  color: ColorUtil.color("#999999"),
                  size: 16,
                ),
              )
            ],
          ),
        ));
  }

  @override
  OffineExamineBloc generateBloc() {
    return OffineExamineBloc();
  }
}
